package cn.yitun.chat.yitunchatnettysdk.netty.web;

import cn.yitun.chat.yitunchatbasesdk.server.im.dispatcher.handler.SessionHandler;
import cn.yitun.chat.yitunchatbasesdk.server.im.dispatcher.handler.SessionMessageHandler;
import cn.yitun.chat.yitunchatnettysdk.netty.common.session.WebSocketSession;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	private WebSocketSession webSocketSession;
	private SessionMessageHandler messageHandler;
	private SessionHandler sessionHandler;

	public WebSocketFrameHandler(SessionMessageHandler messageHandler, SessionHandler sessionHandler) {
		this.messageHandler = messageHandler;
		this.sessionHandler = sessionHandler;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
		if (frame instanceof TextWebSocketFrame) {
			String message = ((TextWebSocketFrame) frame).text();
			messageHandler.onMessage(message, webSocketSession);
		}
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		webSocketSession = new WebSocketSession(ctx);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		sessionHandler.removeSession(webSocketSession);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("新连接");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug((null != webSocketSession) ? webSocketSession.getKey().toString() : "" + "：空闲");
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		// ctx.close();
	}
}
